package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.Exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    @Autowired
    SpecParamService paramService;
    @Override
    public List<SpecGroupDTO> queryGroupByCategoryId(Long categoryId) {
        List<SpecGroup> list = query().eq("category_id", categoryId).list();
        //转化成DTO
        return SpecGroupDTO.convertEntityList(list);
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long categoryId) {
        //1.查询规格组
        List<SpecGroupDTO> groupDTOList = queryGroupByCategoryId(categoryId);
        //1.1健壮性判断
        if (CollectionUtils.isEmpty(groupDTOList)){
            throw new LyException("商品规格组不存在",404);
        }
        List<SpecParamDTO> paramList = paramService.queryParams(categoryId, null, null);
        //2.把这些param根据groupIdf分组,groupId一致的放到一组,形成一个map
        //Map的key就是groupId 值是groupId一致的所有的param的集合
       /* Map<Long,List<SpecParamDTO>> map=new HashMap<>();
        for (SpecParamDTO param : paramList) {
            Long groupId = param.getGroupId();
            //判断在map中是否已经存在
            if (!map.containsKey(groupId)){
                //如果不存在,在map中创建新的List集合
                map.put(groupId,new ArrayList<>());
                //把param放到这个List
                boolean add = map.get(groupId).add(param);
            }else {
                //已经存在,直接存入这个List
                map.get(groupId).add(param);
            }
        }*/
        Map<Long, List<SpecParamDTO>> map = paramList.stream().collect(Collectors.groupingBy(SpecParamDTO::getCategoryId));
        //3.给规格组内填充规格参数
        for (SpecGroupDTO groupDTO : groupDTOList) {
            //获取组id
            Long groupId = groupDTO.getId();
            //根据组id去map中拿
            List<SpecParamDTO> params = map.get(groupId);
            //设置规格参数
            groupDTO.setParams(params);

        }
        return groupDTOList;

    }
}